import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.List;


// 学生管理系统主界面
public class StudentManagementSystem extends JFrame {
    private List<Student> students = new ArrayList<>();
    private DefaultListModel<Student> listModel = new DefaultListModel<>();
    private JList<Student> studentList;
    private int currentPage = 0;
    private final int PAGE_SIZE = 10;

    public StudentManagementSystem() {
        // 初始化测试数据
        initializeTestData();

        // 设置窗口
        setTitle("学生管理系统");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 创建UI组件
        createUIComponents();

        // 刷新学生列表显示
        refreshStudentList();
    }

    private void initializeTestData() {
        students.add(new Student("001", "张三", "男", 20, "计科1班", "2023-09-01"));
        students.add(new Student("002", "李四", "男", 21, "计科1班", "2023-09-01"));
        students.add(new Student("003", "王五", "女", 20, "计科1班", "2023-09-01"));
    }

    private void createUIComponents() {
        // 创建主面板
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());
        mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 顶部按钮面板
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));

        JButton addButton = new JButton("追加学生");
        JButton deleteButton = new JButton("删除学生");
        JButton updateButton = new JButton("更新学生");

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);

        // 学生列表
        studentList = new JList<>(listModel);
        studentList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        studentList.setCellRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                                                          boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                Student student = (Student) value;
                setText(String.format("%s - %s - %s - %d岁 - %s - %s",
                        student.getId(), student.getName(), student.getGender(),
                        student.getAge(), student.getClassName(), student.getEnrollmentDate()));
                return this;
            }
        });

        JScrollPane listScrollPane = new JScrollPane(studentList);

        // 底部导航面板
        JPanel navigationPanel = new JPanel();
        navigationPanel.setLayout(new FlowLayout(FlowLayout.CENTER));

        JButton prevButton = new JButton("前一页");
        JButton nextButton = new JButton("后一页");
        JLabel pageLabel = new JLabel();

        navigationPanel.add(prevButton);
        navigationPanel.add(pageLabel);
        navigationPanel.add(nextButton);

        // 添加组件到主面板
        mainPanel.add(buttonPanel, BorderLayout.NORTH);
        mainPanel.add(listScrollPane, BorderLayout.CENTER);
        mainPanel.add(navigationPanel, BorderLayout.SOUTH);

        // 添加主面板到窗口
        add(mainPanel);

        // 更新页码标签
        updatePageLabel(pageLabel);

        // 添加按钮事件监听
        addButton.addActionListener(e -> showAddStudentDialog());

        deleteButton.addActionListener(e -> deleteSelectedStudent());

        updateButton.addActionListener(e -> showUpdateStudentDialog());

        prevButton.addActionListener(e -> {
            if (currentPage > 0) {
                currentPage--;
                refreshStudentList();
                updatePageLabel(pageLabel);
            }
        });

        nextButton.addActionListener(e -> {
            if ((currentPage + 1) * PAGE_SIZE < students.size()) {
                currentPage++;
                refreshStudentList();
                updatePageLabel(pageLabel);
            }
        });
    }

    private void updatePageLabel(JLabel pageLabel) {
        int totalPages = (int) Math.ceil((double) students.size() / PAGE_SIZE);
        pageLabel.setText(String.format("第 %d 页，共 %d 页", currentPage + 1, Math.max(1, totalPages)));
    }

    private void refreshStudentList() {
        listModel.clear();
        int startIndex = currentPage * PAGE_SIZE;
        int endIndex = Math.min(startIndex + PAGE_SIZE, students.size());
        for (int i = startIndex; i < endIndex; i++) {
            listModel.addElement(students.get(i));
        }
    }

    private void showAddStudentDialog() {
        JDialog dialog = new JDialog(this, "添加学生", true);
        dialog.setSize(400, 350);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(7, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JTextField idField = new JTextField();
        JTextField nameField = new JTextField();
        JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"男", "女"});
        JTextField ageField = new JTextField();
        JTextField classField = new JTextField();
        JTextField dateField = new JTextField();

        panel.add(new JLabel("学号:"));
        panel.add(idField);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("性别:"));
        panel.add(genderComboBox);
        panel.add(new JLabel("年龄:"));
        panel.add(ageField);
        panel.add(new JLabel("班级:"));
        panel.add(classField);
        panel.add(new JLabel("入学日期:"));
        panel.add(dateField);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                String id = idField.getText().trim();
                String name = nameField.getText().trim();
                String gender = (String) genderComboBox.getSelectedItem();
                int age = Integer.parseInt(ageField.getText().trim());
                String className = classField.getText().trim();
                String date = dateField.getText().trim();

                if (id.isEmpty() || name.isEmpty() || className.isEmpty() || date.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写完整信息", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                students.add(new Student(id, name, gender, age, className, date));
                refreshStudentList();
                dialog.dispose();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "年龄必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    private void deleteSelectedStudent() {
        Student selectedStudent = studentList.getSelectedValue();
        if (selectedStudent == null) {
            JOptionPane.showMessageDialog(this, "请先选择要删除的学生", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        int confirm = JOptionPane.showConfirmDialog(this,
                "确定要删除 " + selectedStudent.getName() + " 吗?",
                "确认删除", JOptionPane.YES_NO_OPTION);

        if (confirm == JOptionPane.YES_OPTION) {
            students.remove(selectedStudent);
            if (currentPage > 0 && currentPage * PAGE_SIZE >= students.size()) {
                currentPage--;
            }
            refreshStudentList();
        }
    }

    private void showUpdateStudentDialog() {
        Student selectedStudent = studentList.getSelectedValue();
        if (selectedStudent == null) {
            JOptionPane.showMessageDialog(this, "请先选择要更新的学生", "提示", JOptionPane.INFORMATION_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "更新学生信息", true);
        dialog.setSize(400, 350);
        dialog.setLocationRelativeTo(this);
        dialog.setLayout(new BorderLayout());

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(7, 2, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JTextField idField = new JTextField(selectedStudent.getId());
        JTextField nameField = new JTextField(selectedStudent.getName());
        JComboBox<String> genderComboBox = new JComboBox<>(new String[]{"男", "女"});
        genderComboBox.setSelectedItem(selectedStudent.getGender());
        JTextField ageField = new JTextField(String.valueOf(selectedStudent.getAge()));
        JTextField classField = new JTextField(selectedStudent.getClassName());
        JTextField dateField = new JTextField(selectedStudent.getEnrollmentDate());

        // 学号不可编辑
        idField.setEditable(false);

        panel.add(new JLabel("学号:"));
        panel.add(idField);
        panel.add(new JLabel("姓名:"));
        panel.add(nameField);
        panel.add(new JLabel("性别:"));
        panel.add(genderComboBox);
        panel.add(new JLabel("年龄:"));
        panel.add(ageField);
        panel.add(new JLabel("班级:"));
        panel.add(classField);
        panel.add(new JLabel("入学日期:"));
        panel.add(dateField);

        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);

        dialog.add(panel, BorderLayout.CENTER);
        dialog.add(buttonPanel, BorderLayout.SOUTH);

        saveButton.addActionListener(e -> {
            try {
                String name = nameField.getText().trim();
                String gender = (String) genderComboBox.getSelectedItem();
                int age = Integer.parseInt(ageField.getText().trim());
                String className = classField.getText().trim();
                String date = dateField.getText().trim();

                if (name.isEmpty() || className.isEmpty() || date.isEmpty()) {
                    JOptionPane.showMessageDialog(dialog, "请填写完整信息", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                selectedStudent.setName(name);
                selectedStudent.setGender(gender);
                selectedStudent.setAge(age);
                selectedStudent.setClassName(className);
                selectedStudent.setEnrollmentDate(date);

                refreshStudentList();
                dialog.dispose();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "年龄必须是数字", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        dialog.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            StudentManagementSystem system = new StudentManagementSystem();
            system.setVisible(true);
        });
    }
}    